<template>
    <div class="app-container">
        <ViewLayoutSearchArea>
            <el-form ref="searchFormRef" :inline="true" :model="hintTextData">
                <el-form-item prop="name" label="搜索框默认文案">
                    <el-input v-model="hintTextData.name" disabled placeholder="请输入关键词" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleUpdateDialog()">修改文案</el-button>
                </el-form-item>
            </el-form>
        </ViewLayoutSearchArea>
        <el-card v-loading="loading" shadow="never">
            <ViewLayoutToolbarArea>
                <div></div>
                <div>
                    <el-button type="primary" @click="dialogVisible = true">新建</el-button>
                </div>
            </ViewLayoutToolbarArea>
            <ViewLayoutTableArea>
                <el-table :data="tableData">
                    <el-table-column prop="name" label="热区气泡名称" align="center" />
                    <el-table-column prop="isPopular" label="是否展示热度" align="center">
                        <template #default="{row}">
                            <el-tag v-if="row.isPopular" type="success" effect="plain">是</el-tag>
                            <el-tag v-else type="danger" effect="plain">否</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="order" label="排序" align="center" />
                    <el-table-column fixed="right" label="操作" width="150" align="center">
                        <template #default="scope">
                            <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)"
                                >编辑</el-button
                            >
                            <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)"
                                >删除</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </ViewLayoutTableArea>
            <ViewLayoutPagerArea>
                <el-pagination
                    background
                    :layout="paginationData.layout"
                    :page-sizes="paginationData.pageSizes"
                    :total="paginationData.total"
                    :page-size="paginationData.pageSize"
                    :current-page="paginationData.currentPage"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </ViewLayoutPagerArea>
        </el-card>
        <!-- 编辑默认搜索文案弹窗 -->
        <el-dialog v-model="dialogVisibleText" :title="'修改热区气泡'" width="600" @close="resetTextForm">
            <el-form
                ref="formRefText"
                :model="formDataText"
                :rules="formRulesText"
                label-width="120px"
                label-position="right"
            >
                <el-form-item prop="name" label="文案名称">
                    <el-input v-model="formDataText.name" placeholder="请输入文案" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisibleText = false">取消</el-button>
                <el-button type="primary" @click="handleUpdateText">确认</el-button>
            </template>
        </el-dialog>
        <!-- 新增/编辑 -->
        <el-dialog
            v-model="dialogVisible"
            :title="currentUpdateId === undefined ? '新建热区气泡 ' : '编辑热区气泡'"
            width="600"
            @close="resetForm"
        >
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
                <el-form-item prop="type" label="类型">
                    <el-select v-model="formData.type" placeholder="请选择类型" @change="handleSearchAction">
                        <el-option
                            v-for="item in tagOptionData"
                            :key="item.type"
                            :label="item.name"
                            :value="item.type"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item prop="name" label="名称">
                    <el-select
                        v-model="formData.name"
                        placeholder="请选择类型"
                        filterable
                        :disabled="isChangePageModule"
                        @change="(val:any) => handleSearchType(val)"
                    >
                        <el-option
                            v-for="item in TagTypeOptionData"
                            :key="item.id"
                            :label="item.name"
                            :value="item.name"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item prop="url" label="跳转URL">
                    <el-input v-model="formData.url" disabled placeholder="请输入URL" />
                </el-form-item>
                <el-form-item prop="order" label="排序">
                    <el-input-number
                        v-model="formData.order"
                        controls-position="right"
                        value-on-clear="null"
                        placeholder="请输入排序"
                    />
                </el-form-item>
                <el-form-item prop="isPopular" label="是否展示热度">
                    <el-radio-group v-model="formData.isPopular">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleCreate">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {reactive, ref, onMounted, watch} from 'vue';
import {
    addTableDataApi,
    deleteTableDataApi,
    updateTableDataApi,
    getTableDataApi,
    getHotZoneDetailApi,
    addTextApi,
    searchTextApi
} from '@/api/hot-zone-recommendation/index';
import {type GetTableData} from '@/api/hot-zone-recommendation/types/hot-zone-recommendation';
import {type FormInstance, type FormRules, ElMessage, ElMessageBox} from 'element-plus';
import {usePagination} from '@/hooks/usePagination';
import type {GetTagData} from '@/api/common/types/common';
import {getTagOptionApi} from '@/api/common/index';
import {
    ViewLayoutSearchArea,
    ViewLayoutToolbarArea,
    ViewLayoutTableArea,
    ViewLayoutPagerArea
} from '@/layout/components';
import {CreateTableRequestData} from '@/api/hot-zone-recommendation/types/hot-zone-recommendation';
import {tagOptionData} from '@/constants/common';

defineOptions({
    name: 'HotZoneRecommendation'
});

const loading = ref<boolean>(false);
const {paginationData, handleCurrentChange, handleSizeChange} = usePagination();
const hintTextData = reactive({
    name: ''
});
const formData = reactive<CreateTableRequestData>({
    type: '',
    name: '',
    url: '',
    value: null,
    order: null,
    isPopular: false
});
const formDataText = reactive({
    name: ''
});
const TagTypeOptionData = ref<GetTagData[]>([]);
const dialogVisible = ref<boolean>(false);
const isChangePageModule = ref<boolean>(true);
const dialogVisibleText = ref<boolean>(false);
const searchFormRef = ref<InstanceType<typeof FormInstance>>();
const formRef = ref<InstanceType<typeof FormInstance>>();
const tableData = ref<GetTableData[]>([]);
const currentUpdateId = ref<undefined | number>(undefined);

// 表单 rules 规则
const formRules = reactive({
    type: [{required: true, trigger: 'change', message: '请选择类型'}],
    name: [{required: true, trigger: 'blur', message: '请输入名称'}],
    value: [{required: true, trigger: 'blur', message: '请输入跳转URL'}],
    order: [{required: true, trigger: 'blur', message: '请输入排序'}],
    isPopular: [{required: true, trigger: 'blur', message: '请输入是否展示热度'}]
});

// 搜索框默认文案表单 rules 规则
const formRulesText = reactive({
    name: [{required: true, trigger: 'blur', message: '请输入文案'}]
});

// 选中模块
const handleSearchAction = (type: string) => {
    const newType = type.toLowerCase();
    const newItem = {
        // keyWord: formData.type
        keyWord: ''
    };
    getTagOptionApi(newItem, newType)
        .then(({data: res}) => {
            if (res.code === 100000) {
                TagTypeOptionData.value = res.data;
                isChangePageModule.value = false;
            }
        })
        .catch(() => {
            TagTypeOptionData.value = [];
            isChangePageModule.value = true;
        });
};

// 选中类型
const handleSearchType = (name: any) => {
    for (const obj of TagTypeOptionData.value) {
        if (obj.name === name) {
            formData.url = obj.content;
            formData.value = obj.id;
            return;
        }
    }
};

const handleCreate = () => {
    formRef.value?.validate((valid: boolean, fields: any) => {
        if (valid) {
            if (currentUpdateId.value === undefined) {
                addTableDataApi(formData)
                    .then(({data: res}) => {
                        if (res.code === 100000) {
                            ElMessage.success('新增成功');
                            getTableData();
                        } else {
                            ElMessage.error(res.data);
                        }
                    })
                    .finally(() => {
                        dialogVisible.value = false;
                    });
            } else {
                updateTableDataApi({
                    id: currentUpdateId.value,
                    ...formData
                })
                    .then(({data: res}) => {
                        if (res.code === 100000) {
                            ElMessage.success('修改成功');
                            getTableData();
                        } else {
                            ElMessage.error(res.data);
                        }
                    })
                    .finally(() => {
                        dialogVisible.value = false;
                    });
            }
        } else {
            console.error('表单校验不通过', fields);
        }
    });
};

// 删除
const handleDelete = (row: GetTableData) => {
    ElMessageBox.confirm(`确认删除热区气泡？`, '删除后不可恢复，你还要继续吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteTableDataApi(row.id).then(({data: res}) => {
            if (res.code === 100000) {
                ElMessage.success('删除成功');
                getTableData();
            } else {
                ElMessage.error(res.data);
            }
        });
    });
};

// 编辑
const handleUpdate = (row: GetTableData) => {
    const {id} = row;
    currentUpdateId.value = id;
    const newItem = {
        id
    };
    // 查询气泡详情
    getHotZoneDetailApi(newItem)
        .then(({data: res}) => {
            const {code, data} = res;
            if (code === 100000) {
                const {type, name, content, order, value, isPopular} = data;
                Object.assign(formData, {type, name, url: content, order, value, isPopular});
            } else {
                ElMessage.error(data);
            }
        })
        .catch(() => {
            ElMessage.error('请求服务出错');
        })
        .finally(() => {
            dialogVisible.value = true;
        });
};

// 查询列表数据
const getTableData = () => {
    loading.value = true;
    const newItem = {
        page: paginationData.currentPage,
        size: paginationData.pageSize
    };
    getTableDataApi(newItem)
        .then(({data: res}) => {
            if (res.code === 100000) {
                const {content = [], number, totalElements} = res.data;
                tableData.value = content;
                paginationData.currentPage = number; //  当前页码
                paginationData.total = totalElements; // 总数
            }
        })
        .catch(() => {
            tableData.value = [];
        })
        .finally(() => {
            loading.value = false;
        });
};

const handleUpdateDialog = () => {
    dialogVisibleText.value = true;
    formDataText.name = hintTextData.name;
};

// 提示搜索文案更新
const handleUpdateText = () => {
    const newItem = {
        hintText: formDataText.name
    };
    addTextApi(newItem)
        .then(({data: res}) => {
            const {code, data} = res;
            if (code === 100000) {
                ElMessage.success('修改成功');
                getSearchText();
            } else {
                ElMessage.error(data);
            }
        })
        .catch(() => {
            ElMessage.error('修改失败，请重试');
        })
        .finally(() => {
            dialogVisibleText.value = false;
        });
};

// 获取搜索框默认文案
const getSearchText = () => {
    searchTextApi()
        .then(({data: res}) => {
            const {code, data} = res;
            if (code === 100000) {
                hintTextData.name = data;
            }
        })
        .catch(() => {
            ElMessage.error('获取搜索框默认文案失败');
        });
};

// 重置新建/编辑表单
const resetForm = () => {
    currentUpdateId.value = undefined;
    formRef.value?.resetFields();
    formData.type = '';
    formData.name = '';
    formData.url = '';
    formData.value = null;
    formData.order = null;
    formData.isPopular = false;
};

// 重置
const resetTextForm = () => {
    formData.name = '';
};

onMounted(() => {
    getSearchText();
});

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, {immediate: true});
</script>

<style lang="less" scoped>
.search-wrapper {
    margin-bottom: 20px;
    :deep(.el-card__body) {
        padding-bottom: 2px;
    }
}

.toolbar-wrapper {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.table-wrapper {
    margin-bottom: 20px;
}

.pager-wrapper {
    display: flex;
    justify-content: flex-end;
}
</style>
